<template>
  <div class="copy-campaign">
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :show-close="false"
      top="114px"
      :modal="false">
      <div class="root">
        <div class="campaign-card">
          <el-card>
            <span slot="header"><div style="float: left">批量复制广告组</div><div style="float: right"><el-button
              type="text" size="mini" icon="el-icon-close" @click="dialogVisible=false" circle></el-button></div><div
              style="clear: both"></div></span>
            <el-form ref="form" :model="campaignForm" label-width="120px" :rules="rules">
              <el-form-item label="广告账户" prop="platformId">
                <el-select style="width: 100%" size="mini" v-model="campaignForm.platformId" placeholder="请选择活动账户"
                           @change="handleChangePlatform" v-loading="platformLoading" :disabled="options.campaignAppProfilePageState === 'ON'">
                  <el-option
                    v-for="item in accountList"
                    :key="item.id"
                    :value="item.platformId"
                    :label="item.name+'ID:'+item.platformId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-radio-group v-model="campaignForm.createType">
                  <el-radio :label="1">到现有推广系列</el-radio>
                  <el-radio :label="2">到新的推广系列</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item prop="campaignId" v-if="campaignForm.createType === 1">
                <el-select v-model="campaignForm.campaignId"
                           style="width: 100%"
                           placeholder="请选择" size="mini"
                           filterable
                           @change="handleChangeCampaign" :disabled="campaignListLoading"
                           v-loading="campaignListLoading">
                  <el-option v-for="item in campaignList" :key="item.id" :label="item.campaignName"
                             :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="推广系列名称" prop="campaignName" v-else>
                <el-input size="mini" v-model="campaignForm.campaignName"></el-input>
              </el-form-item>
              <el-form-item label="复制数量">
                <el-input-number size="mini" v-model="campaignForm.num" :disabled="true"></el-input-number>
              </el-form-item>
              <el-form-item label="APP">
                <el-image :src="options.os === 1 ? androidImage: iosImage"
                          style="height: 25px;width: 25px;vertical-align: middle"></el-image>&nbsp;{{ options.appName }}
                <el-checkbox v-show="campaignForm.createType === 2" v-model="campaignForm.ios14Camppaign"
                             style="margin-left: 30px"
                             :disabled="options.os ===1" @change="handleChangeIos14Switch">iOS 14
                </el-checkbox>
              </el-form-item>
              <el-form-item label="预算" prop="budget">
                <el-input
                  size="mini"
                  v-model="campaignForm.budget" class="input-with-select" :disabled="campaignForm.createType === 1"
                  placeholder="50.00以上"
                  oninput="if(isNaN(value)){value=null} if(value.indexOf(0) === 0 && value.charAt(1) !== '.'){value=0} if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}">
                  <el-select style="width: 100px" id="AdGroupBudgetChange" v-model="campaignForm.budgetMode"
                             slot="prepend" placeholder="预算模式"
                             :disabled="campaignForm.createType === 1">
                    <el-option v-for="item in budgetModeList" :key="item.value" :label="item.label"
                               :value="item.value"></el-option>
                  </el-select>
                  <template slot="append">USD</template>
                </el-input>
              </el-form-item>
              <el-form-item label="推广目标">
                应用推广
              </el-form-item>
              <el-row justify="center" type="flex" align="middle">
                <!--<el-button size="mini" type="primary" @click="confirmCopyCampaign">确认复制</el-button>-->
                <!--<el-button size="mini" @click="dialogVisible = false">取消</el-button>-->
              </el-row>
              <el-collapse-transition>
                <div v-show="adGroupTableData.length>0">
                  <el-divider></el-divider>
                  <el-table
                    :data="adGroupTableData"
                    :key="tKey"
                    style="width: 100%">
                    <el-table-column
                      prop="adgroupName"
                      label="广告组名"
                      :show-overflow-tooltip="true">
                    </el-table-column>
                    <el-table-column
                      label="操作"
                      width="100">
                      <template v-slot="{row,$index}">
                        <el-button type="text" @click="editAdGroup(row)">编辑</el-button>
                        <el-button type="text" @click="delAdGroup($index)">删除</el-button>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="isEdit"
                      label="状态"
                      width="100">
                      <template v-slot="{row}">
                        {{ row.isEdit }}
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-row style="margin-top:10px" justify="center" type="flex" align="middle">
                    <el-button size="mini" type="primary" @click="submitForm" v-loading="submitCampaignLoading">发布并暂停
                    </el-button>
                  </el-row>
                </div>
              </el-collapse-transition>
            </el-form>
          </el-card>
        </div>
        <el-drawer
          :visible.sync="editAdGroupDrawer"
          :modal="false"
          size="calc(100vw - 720px)"
          :destroy-on-close="true"
          :close-on-click-modal="false"
          :with-header="false">
          <cs-drawer-container>
            <div class="edit-ad-group-box">
              <div class="edit-ad-group-box-left">
                <el-card>
                  <span slot="header">编辑广告组</span>
                  <ad-group-form ref="adGroupForm" :options="adGroupOptions"
                                 :current-account-id="campaignForm.platformId"></ad-group-form>
                </el-card>
              </div>
              <div class="edit-ad-group-box-right">
                <el-card v-for="(item, index) in adGroupOptions.ttAdList" style="margin-bottom: 10px" :key="index">
                  <div slot="header" class="clearfix">
                    <span></span>
                    <el-button v-show="adGroupOptions.creativeMaterialMode === 'CUSTOM'"
                               style="float: right; padding: 3px 0;color: #F56C6C; margin-left: 10px" type="text"
                               @click="delAd(index)">删除
                    </el-button>
                    <el-button style="float: right; padding: 3px 0" type="text" @click="editAd(item)">修改</el-button>
                  </div>
                  <el-descriptions :column="1">
                    <el-descriptions-item label="广告名">{{ item.adName }}</el-descriptions-item>
                    <el-descriptions-item label="广告ID">{{ item.ttAdId }}</el-descriptions-item>
                  </el-descriptions>
                </el-card>
              </div>
            </div>
            <template v-slot:bottom>
              <el-button slot="bottom" size="mini" @click="editAdGroupDrawer = false">取消</el-button>
              <el-button slot="bottom" size="mini" type="primary" @click="handleSaveAdGroup">保存</el-button>
            </template>
          </cs-drawer-container>
          <el-drawer
            :visible="editAdDrawer"
            :append-to-body="true"
            :modal="false"
            :close-on-click-modal="false"
            :with-header="false"
            size="46%"
            class="append-to-body"
          >
            <cs-drawer-container>
              <div class="creative-drawer-box">
                <ad-form v-if="editAdDrawer" ref="adForm" :options="adOptions"
                         :platform-app-id="options.appId" :ad-group="adGroupOptions"
                         :is-origin-account="isOriginAccount" :campaign="options"
                         :current-account-id="campaignForm.platformId"></ad-form>
              </div>
              <template v-slot:bottom>
                <el-button slot="bottom" size="mini" @click="editAdDrawer = false">取消</el-button>
                <el-button slot="bottom" size="mini" type="primary" @click="handleSaveAd">保存</el-button>
              </template>
            </cs-drawer-container>
          </el-drawer>
        </el-drawer>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import AdGroupForm from "@/views/campaign-management/components/AdGroupForm";
import {
  confirmCopyCampaign,
  createAdCampaign, createBatchAdGroup, getCampaignList, getIos14Quota,
} from "@/api/campaign-management/campaign-management";
import {getActiveAccountList} from "@/api/campaign/campaign";
import AdForm from "@/views/campaign-management/components/AdForm";
import Moment from "moment";

export default {
  name: "AdGroupClone",
  components: {
    CsDrawerContainer,
    AdGroupForm,
    AdForm
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    options: {
      type: Object
    },
    offerId: {
      type: String
    },
    copyAdGroupList: {
      type: Array
    }
  },
  created() {
    this.getActiveAccountList()
    this.getCampaignList()
    this.adGroupTableData = this.copyAdGroupList.map(item => {
      item.isEdit = '待修改'
      item.scheduleStartTime = Moment().utc().add(this.options.timezoneOffset, "hours").format("yyyy-MM-DD HH:mm:ss")
      item.scheduleEndTime = Moment().utc().add(this.options.timezoneOffset, "hours").add(14, "days").format("yyyy-MM-DD HH:mm:ss")
      return item
    })
    if (this.options.campaignAppProfilePageState === 'ON'){
      this.campaignForm.platformId = this.options.platformId
    }
  },
  data() {
    var checkCampaignName = (rule, value, callback) => {
      if (this.campaignForm.createType === 2) {
        if (value === '') {
          callback(new Error('请输入推广系列名称'));
        } else {
          callback()
        }
      } else {
        callback()
      }

    };
    var checkCampaignId = (rule, value, callback) => {
      if (this.campaignForm.createType === 1) {
        if (value === '') {
          callback(new Error('请选择推广系列'));
        } else {
          callback()
        }
      } else {
        callback()
      }
    };
    var validateCampaignBudget = (rule, value, callback) => {
      if (this.campaignForm.budgetMode !== 'BUDGET_MODE_INFINITE') {
        if (value === '') {
          callback(new Error('请输入预算'))
        } else if (parseInt(value) < 50 || parseInt(value) > 10000000) {
          callback(new Error('预算应为 50.00 - 10,000,000.00间的纯数字'))
        } else if (this.campaignForm.budgetMode === '') {
          callback(new Error('请选择预算模式'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      campaignForm: {
        campaignId: '',
        campaignName: '',
        num: 1,
        platformId: '',
        budget: '',
        createType: 1,
        budgetMode: '',
        ios14Camppaign: false
      },
      adGroupTableData: [],
      editAdGroupDrawer: false,
      accountList: [],
      rules: {
        platformId: [
          {required: true, message: '请选择账户', trigger: 'change'}
        ],
        campaignName: [
          {validator: checkCampaignName, trigger: 'blur'},
        ],
        campaignId: [
          {validator: checkCampaignId, trigger: 'change'}
        ],
        budget: [{validator: validateCampaignBudget, trigger: 'blur'}]
      },
      adGroupOptions: {
        ttAdList: [],
      },
      adForm: {},
      editAdDrawer: false,
      adOptions: null,
      submitCampaignLoading: false,
      budgetModeList: [{
        label: '日预算',
        value: 'BUDGET_MODE_DAY'
      }, {
        label: '总预算',
        value: 'BUDGET_MODE_TOTAL'
      },
        {
          label: '不限预算',
          value: 'BUDGET_MODE_INFINITE'
        }],
      isOriginAccount: false,
      levelQuota: {},
      campaignList: [],
      platformLoading: false,
      campaignListLoading: false,
      androidImage: '',
      iosImage: '',
      tKey: 0
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val || false)
      }
    }
  },
  methods: {
    async getActiveAccountList() {
      this.platformLoading = true
      const {data: res} = await getActiveAccountList(this.offerId).finally(() => {
        this.platformLoading = false
      })
      this.accountList = res.data
    },
    // 初始化
    handleOpenDialog() {
      this.campaignForm.campaignName = this.options.campaignName + '-copy'
      this.campaignForm.campaignId = this.options.id
      this.campaignForm.budget = this.options.budget
      this.campaignForm.budgetMode = this.options.budgetMode
      this.getActiveAccountList()
    },
    // confirmCopyCampaign() {
    //   this.$refs.form.validate(async valid => {
    //     if (!valid) return
    //     if (this.options.campaignAppProfilePageState === 'ON') {
    //       if (!this.isOriginAccount) return this.$message.error('APPO广告只允许复制到当前账户')
    //       await this.getLevelQuota()
    //       if (this.levelQuota.campaignQuota.availableQuota === 0) return this.$message.error('应用已达到 iOS 14 专属推广系列限额。 要创建新推广系列，请删除或关闭现有的某个推广系列')
    //     }
    //     const {data: res} = await confirmCopyCampaign({
    //       campaignId: this.campaignForm.campaignId,
    //       newCampaignName: this.campaignForm.campaignName,
    //       platformId: this.campaignForm.platformId
    //     })
    //     this.adGroupTableData = res.data.map(item => {
    //       item.isEdit = '待修改'
    //       if (!this.isOriginAccount) {
    //         item.ttAdList.forEach(ad => {
    //           ad.identityId = ad.adIdentityName
    //           ad.pageId = ''
    //           ad.landingPageUrl = ''
    //         })
    //       }
    //       return item
    //     })
    //   })
    // },
    editAdGroup(row) {
      this.adGroupOptions = row
      this.editAdGroupDrawer = true
    },
    editAd(row) {
      this.adOptions = row
      this.editAdDrawer = true
    },
    handleSaveAd() {
      this.$refs.adForm.$refs.adForm.validate(valid => {
        if (!valid) return
        if (this.adOptions.creativeMaterialMode === 'DYNAMIC') {
          if (this.$refs.adForm.adForm.callToActionType == '0' && this.$refs.adForm.acoCTAs.length === 0) return this.$message.error('CTA不能为空')
          const ttAdList = []
          let step = 1
          this.$refs.adForm.acoCreatives.forEach(creative => {
            this.$refs.adForm.acoAdTexts.forEach(text => {
              if (this.$refs.adForm.adForm.callToActionType === '1') {
                ttAdList.push(
                  {
                    "adName": creative.name + "-" + (step++),
                    "identityId": this.$refs.adForm.adForm.identityId,
                    "autoCreateType": this.$refs.adForm.adForm.autoCreateType,
                    "adFormat": this.$refs.adForm.adForm.adFormat,
                    "callToActionType": this.$refs.adForm.adForm.callToActionType,
                    "impressionTrackingUrl": this.$refs.adForm.adForm.impressionTrackingUrl,
                    "clickTrackingUrl": this.$refs.adForm.adForm.clickTrackingUrl,
                    "creativeList": this.$refs.adForm.adForm.creativeList,
                    "adText": text,
                    "callToAction": '',
                    "adIdentityName": this.$refs.adForm.adForm.adIdentityName,
                    "creativeId": creative.id,
                    "creativeType": creative.type,
                    "platformId": this.$refs.adForm.adForm.platformId,
                    "landingPageUrl": this.$refs.adForm.adForm.landingPageUrl,
                    "pageId": this.$refs.adForm.adForm.pageId
                  }
                )
              } else {
                this.$refs.adForm.acoCTAs.forEach(cta => {
                  ttAdList.push(
                    {
                      "adName": creative.name + "-" + (step++),
                      "identityId": this.$refs.adForm.adForm.identityId,
                      "autoCreateType": this.$refs.adForm.adForm.autoCreateType,
                      "adFormat": this.$refs.adForm.adForm.adFormat,
                      "callToActionType": this.$refs.adForm.adForm.callToActionType,
                      "impressionTrackingUrl": this.$refs.adForm.adForm.impressionTrackingUrl,
                      "clickTrackingUrl": this.$refs.adForm.adForm.clickTrackingUrl,
                      "creativeList": this.$refs.adForm.adForm.creativeList,
                      "adText": text,
                      "callToAction": cta,
                      "adIdentityName": this.$refs.adForm.adForm.adIdentityName,
                      "creativeId": creative.id,
                      "creativeType": creative.type,
                      "platformId": this.$refs.adForm.adForm.platformId,
                      "landingPageUrl": this.$refs.adForm.adForm.landingPageUrl,
                      "pageId": this.$refs.adForm.adForm.pageId
                    }
                  )
                })
              }
            })
          })
          this.adGroupOptions.ttAdList = ttAdList
          this.adGroupOptions.acoCreatives = this.$refs.adForm.acoCreatives
          this.adGroupOptions.acoCTAs = this.$refs.adForm.acoCTAs
          this.adGroupOptions.acoAdTexts = this.$refs.adForm.acoAdTexts
        } else {
          this.adOptions.adName = this.$refs.adForm.adForm.adName
          this.adOptions.identityId = this.$refs.adForm.adForm.identityId
          this.adOptions.autoCreateType = this.$refs.adForm.adForm.autoCreateType
          this.adOptions.adFormat = this.$refs.adForm.adForm.adFormat
          this.adOptions.callToActionType = this.$refs.adForm.adForm.callToActionType
          this.adOptions.impressionTrackingUrl = this.$refs.adForm.adForm.impressionTrackingUrl
          this.adOptions.clickTrackingUrl = this.$refs.adForm.adForm.clickTrackingUrl
          this.adOptions.creativeList = this.$refs.adForm.adForm.creativeList
          this.adOptions.adText = this.$refs.adForm.adForm.adText
          this.adOptions.callToAction = this.$refs.adForm.adForm.callToAction
          this.adOptions.adIdentityName = this.$refs.adForm.adForm.adIdentityName
          this.adOptions.creativeId = this.$refs.adForm.adForm.creativeId
          this.adOptions.platformId = this.$refs.adForm.adForm.platformId
          this.adOptions.landingPageUrl = this.$refs.adForm.adForm.landingPageUrl
          this.adOptions.pageId = this.$refs.adForm.adForm.pageId
          this.adOptions.creativeType = this.$refs.adForm.adForm.creativeType
        }
        this.$set(this.adGroupOptions, 'isEdit', '已保存')
        this.tKey = Math.floor(Math.random() * 1000)
        this.adGroupOptions.isEditAd = true
        this.editAdDrawer = false
      })

    },
    handleSaveAdGroup() {
      this.$refs.adGroupForm.$refs.adGroupForm.validate(valid => {
        if (!valid) return
        this.adGroupOptions.adgroupName = this.$refs.adGroupForm.adGroupForm.adgroupName
        this.adGroupOptions.placementType = this.$refs.adGroupForm.adGroupForm.placementType
        this.adGroupOptions.commentDisabled = this.$refs.adGroupForm.adGroupForm.commentDisabled
        this.adGroupOptions.videoDownloadDisabled = this.$refs.adGroupForm.adGroupForm.videoDownloadDisabled
        this.adGroupOptions.creativeMaterialMode = this.$refs.adGroupForm.adGroupForm.creativeMaterialMode
        this.adGroupOptions.gender = this.$refs.adGroupForm.adGroupForm.gender
        this.adGroupOptions.actionPeriod = this.$refs.adGroupForm.adGroupForm.actionPeriod
        this.adGroupOptions.expansionEnabled = this.$refs.adGroupForm.adGroupForm.expansionEnabled
        this.adGroupOptions.budgetMode = this.$refs.adGroupForm.adGroupForm.budgetMode
        this.adGroupOptions.budget = this.$refs.adGroupForm.adGroupForm.budget
        this.adGroupOptions.scheduleType = this.$refs.adGroupForm.adGroupForm.scheduleType
        this.adGroupOptions.scheduleEndTime = this.$refs.adGroupForm.adGroupForm.scheduleEndTime
        this.adGroupOptions.scheduleStartTime = this.$refs.adGroupForm.adGroupForm.scheduleStartTime
        this.adGroupOptions.optimizationGoal = this.$refs.adGroupForm.adGroupForm.optimizationGoal
        this.adGroupOptions.optimizationEvent = this.$refs.adGroupForm.adGroupForm.optimizationEvent
        this.adGroupOptions.bidType = this.$refs.adGroupForm.adGroupForm.bidType
        this.adGroupOptions.roasBid = this.$refs.adGroupForm.adGroupForm.roasBid
        this.adGroupOptions.bidPrice = this.$refs.adGroupForm.adGroupForm.bidPrice
        this.adGroupOptions.conversionBidPrice = this.$refs.adGroupForm.adGroupForm.conversionBidPrice
        this.adGroupOptions.dailyRetentionRatio = this.$refs.adGroupForm.adGroupForm.dailyRetentionRatio
        this.adGroupOptions.pacing = this.$refs.adGroupForm.adGroupForm.pacing
        this.adGroupOptions.platformId = this.$refs.adGroupForm.adGroupForm.platformId
        this.adGroupOptions.appId = this.$refs.adGroupForm.adGroupForm.appId
        this.adGroupOptions.interestCategory = JSON.stringify(this.$refs.adGroupForm.adGroupForm.interestCategory)
        this.adGroupOptions.interestsByKeyword = JSON.stringify(this.$refs.adGroupForm.adGroupForm.interestsByKeyword)
        this.adGroupOptions.videoUserActions = JSON.stringify(this.$refs.adGroupForm.adGroupForm.videoUserActions)
        this.adGroupOptions.videoRelatedCategory = JSON.stringify(this.$refs.adGroupForm.adGroupForm.videoRelatedCategory)
        this.adGroupOptions.creatorRelatedCategory = JSON.stringify(this.$refs.adGroupForm.adGroupForm.creatorRelatedCategory)
        this.adGroupOptions.householdIncome = this.$refs.adGroupForm.adGroupForm.householdIncome.join(',')
        this.adGroupOptions.locationIds = this.$refs.adGroupForm.adGroupForm.locationIds.join(',')
        this.adGroupOptions.placement = this.$refs.adGroupForm.adGroupForm.placement.join(',')
        this.adGroupOptions.age = this.$refs.adGroupForm.adGroupForm.age.join(',')
        this.adGroupOptions.languages = this.$refs.adGroupForm.adGroupForm.languages.join(',')
        this.adGroupOptions.interestCategoryIds = this.$refs.adGroupForm.adGroupForm.interestCategoryIds.join(',')
        this.adGroupOptions.interestsByKeywordIds = this.$refs.adGroupForm.adGroupForm.interestsByKeywordIds.join(',')
        this.adGroupOptions.videoRelatedCategoryIds = this.$refs.adGroupForm.adGroupForm.videoRelatedCategoryIds.join(',')
        this.adGroupOptions.creatorRelatedCategoryIds = this.$refs.adGroupForm.adGroupForm.creatorRelatedCategoryIds.join(',')
        this.adGroupOptions.expansionTypes = this.$refs.adGroupForm.adGroupForm.expansionTypes.join(',')
        this.$set(this.adGroupOptions, 'isEdit', '已保存')
        this.editAdGroupDrawer = false
      })
    },
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        if (this.options.campaignType === 'IOS14_CAMPAIGN') {
          await this.getLevelQuota()
          if (this.levelQuota.adgroupQuota.availableQuota < this.adGroupTableData.length) return this.$message.error('应用已达到 iOS 14 专属广告组限额。 要创建新广告组，请删除或关闭现有的某个广告组')
        }
        if (this.submitCampaignLoading) return
        if (this.adGroupTableData.some(adGroup => {
          return adGroup.ttAdList.some(ad => ad.pageId === '')
        }) && this.options.campaignAppProfilePageState === 'ON') return this.$message.error('广告未指定应用介绍页')
        this.submitCampaignLoading = true
        const adGroups = this.adGroupTableData.map(item => {
          if (item.videoUserActions === '') {
            item.videoUserActions = {
              VIDEO_RELATED: [],
              CREATOR_RELATED: []
            }
          } else {
            item.videoUserActions = JSON.parse(item.videoUserActions)
          }
          const actionScene = []
          if (item.videoUserActions.VIDEO_RELATED.length) {
            actionScene.push('VIDEO_RELATED')
          }
          if (item.videoUserActions.CREATOR_RELATED.length) {
            actionScene.push('CREATOR_RELATED')
          }
          const ttAdList = item.ttAdList.map(ad => {
            return {
              "adName": ad.adName,
              "adText": ad.adText,
              "adFormat": ad.adFormat,
              "callToActionType": ad.callToActionType,
              "callToAction": ad.callToAction,
              "clickTrackingUrl": ad.clickTrackingUrl,
              "creativeId": ad.creativeId,
              "impressionTrackingUrl": ad.impressionTrackingUrl,
              "operationStatus": "DISABLE",
              "identityType": "CUSTOMIZED_USER",
              "identityId": ad.identityId,
              "adIdentityName": ad.adIdentityName,
              "proportion": ad.proportion,
              "creativeType": ad.creativeType,
              "landingPageUrl": ad.landingPageUrl,
              "pageId": ad.pageId
            }
          })
          return {
            "adgroupName": item.adgroupName,
            "age": item.age,
            "gender": item.gender,
            "languages": item.languages,
            "locationIds": item.locationIds,
            "appId": item.appId,
            "autoTargetingEnabled": item.autoTargetingEnabled,
            "bidType": item.bidType,
            "budget": item.budget,
            "budgetMode": item.budgetMode,
            "commentDisabled": item.commentDisabled,
            "householdIncome": item.householdIncome,
            "optimizationEvent": item.optimizationEvent,
            "optimizationGoal": item.optimizationGoal,
            "pacing": item.pacing,
            "placementType": item.placementType,
            "scheduleStartTime": item.scheduleStartTime,
            "scheduleEndTime": item.scheduleEndTime,
            "scheduleType": item.scheduleType,
            "videoDownloadDisabled": item.videoDownloadDisabled,
            "blockedPangleDisabled": item.blockedPangleDisabled,
            "placement": item.placement,
            "interestCategoryIds": item.interestCategoryIds,
            "interestCategory": item.interestCategory,
            "operationStatus": "DISABLE",
            "platformId": item.platformId,
            "billingEvent": item.billingEvent,
            "dailyRetentionRatio": item.dailyRetentionRatio,
            "os": item.os,
            "deepBidType": item.deepBidType,
            "roasBid": item.roasBid,
            "audienceIds": item.audienceIds,
            "excludedAudienceIds": item.excludedAudienceIds,
            "expansionEnabled": item.expansionTypes.length > 0 ? 1 : 0,
            "expansionTypes": item.expansionTypes,
            "videoUserActions": JSON.stringify(item.videoUserActions),
            "actionPeriod": item.actionPeriod,
            "creatorRelatedCategoryIds": item.creatorRelatedCategoryIds,
            "creatorRelatedCategory": item.creatorRelatedCategory,
            "videoRelatedCategoryIds": item.videoRelatedCategoryIds,
            "videoRelatedCategory": item.videoRelatedCategory,
            "creativeMaterialMode": item.creativeMaterialMode,
            "interestsByKeyword": item.interestsByKeyword,
            "interestsByKeywordIds": item.interestsByKeywordIds,
            "bidPrice": item.bidPrice,
            "conversionBidPrice": item.conversionBidPrice,
            "actionScene": actionScene.join(','),
            ttAdList
          }
        })
        const campaign = {
          "budget": this.campaignForm.budget,
          "budgetMode": this.campaignForm.budgetMode,
          "budgetOptimizeSwitch": 0,
          "campaignName": this.campaignForm.campaignName,
          "campaignType": this.campaignForm.ios14Camppaign ? 'IOS14_CAMPAIGN' : 'REGULAR_CAMPAIGN',
          "objectiveType": 'APP_INSTALL',
          "operationStatus": "DISABLE",
          "platformId": this.campaignForm.platformId,
          "offerId": this.offerId,
          "appName": this.options.appName,
          "appId": this.options.appId,
          "os": this.options.os,
        }
        if (this.campaignForm.createType === 1) {
          await createBatchAdGroup(this.campaignForm.campaignId,
            adGroups
          ).finally(() => {
            this.submitCampaignLoading = false
          })
        } else {
          await createAdCampaign({
            campaign,
            adGroups,
          }).finally(() => {
            this.submitCampaignLoading = false
          })
        }


        // console.log({
        //   campaign,
        //   adGroups,
        // })
        this.$message.success('复制成功')
        this.dialogVisible = false
      })

    },
    delAdGroup(index) {
      this.adGroupTableData.splice(index, 1)
    },
    delAd(index) {
      this.adGroupOptions.ttAdList.splice(index, 1)
    },
    handleChangePlatform(val) {
      this.isOriginAccount = this.options.platformId === val
    },
    async getLevelQuota() {
      const {data: res} = await getIos14Quota({
        appId: this.options.appId,
        platformId: this.campaignForm.platformId
      })
      this.levelQuota = res.data
    },
    // 获取所有的campaign列表
    async getCampaignList() {
      this.campaignListLoading = true
      const {data: res} = await getCampaignList({
        offerId: this.offerId,
        campaignTypes: this.options.campaignAppProfilePageState === 'ON' ? 'SPC_0,APPO_ON' : 'SPC_0,APPO_OFF',
        os: this.options.os
      }).finally(() => {
        this.campaignListLoading = false
      })
      this.campaignList = res.data
    },
    handleChangeCampaign(val) {
      const campaign = this.campaignList.find(item => item.id)
      if (campaign !== undefined) {
        console.log(campaign)
        if (campaign.campaignType === 'IOS14_CAMPAIGN') {
          this.checkIos14()
        }
        this.campaignForm.budget = campaign.budget
        this.campaignForm.budgetMode = campaign.budgetMode
      }
    },
    async handleChangeIos14Switch(val) {
      if (val) {
        const {data: res} = await getIos14Quota({
          appId: this.options.appId,
          platformId: this.campaignForm.platformId
        })
        if (res.data.campaignQuota.availableQuota < 1) {
          this.campaignForm.ios14Camppaign = false
          return this.$message.error('应用已达到 iOS 14 专属推广系列限额。 要创建新推广系列，请删除或关闭现有的某个推广系列')
        } else {
          this.levelQuota = res.data
        }
      }
    },
    async checkIos14() {
      const {data: res} = await getIos14Quota({
        appId: this.options.appId,
        platformId: this.campaignForm.platformId
      })
      this.levelQuota = res.data
    }
  }
}
</script>

<style scoped lang="scss">
* {
  box-sizing: border-box;
}

.copy-campaign {
  ::v-deep .el-dialog {
    margin: 0 0 0 216px;
    width: calc(100vw - 220px);
    background: #fff0;
  }

  ::v-deep .el-drawer {
    top: unset;
    height: calc(100vh - 114px);
  }

  ::v-deep .el-dialog__header {
    padding: unset;
  }

  ::v-deep .el-dialog__body {
    padding: unset;
  }

  .root {
    height: calc(100vh - 115px);
    overflow: auto;
    display: flex;

    .campaign-card {
      height: 100%;
      width: 500px;
    }

    .edit-ad-group-box {
      display: flex;
      height: 100%;

      .edit-ad-group-box-left {
        width: 70%;
        overflow: auto;
      }

      .edit-ad-group-box-right {
        width: 30%;
        overflow: auto;
        padding: 20px;
      }
    }
  }
}

.append-to-body {
  ::v-deep .el-drawer {
    top: unset;
    height: calc(100vh - 114px);
  }
}
</style>
